<?php
//include config file
require_once APPLICATION_PATH.'/configs/config.php';
$config['errorReporting'] = $errorReporting;
if ($errorReporting)
    error_reporting(E_ALL);
else
    error_reporting(0);

//session start
if (!session_id())
    session_start();

//ham bat loi thu cong
function handleUncaughtException($e)
{
    global $errorReporting;
    if ($errorReporting)
    {
        echo $e;
    } 
    else
    {
        if($e->getCode() == 404){
            $registry = Core_Registry::singleton();
            $error = $registry['config']['error404'];
            if($error['status']){
                 $path = $registry['baseUrl'].$error['path'];
                 header("Location: $path");
            }
        }
    }
}

set_exception_handler("handleUncaughtException");

function __autoload($class_name)
{
    //chia thanh tung phan
    $parts = explode('_', $class_name);

    $count = count($parts);
    $flag = true;

    if ($count == 0)
        throw new Exception('Unable to load class: ' . $class_name);


    //Model Default
    if ($flag && $count == 2 && $parts[0] == 'Model')
    {
        global $defaultModule;
        $file = APPLICATION_PATH . '/modules/' . $defaultModule . '/models/' . $parts[1] .
            '.php';
        if (!is_readable($file))
            throw new Exception('Unable to load class: ' . $class_name . ' in file :' . $file);
        include_once ($file);
        $flag = false;
    }

    //Other Model
    if ($flag && $count == 3 && $parts[1] == 'Model')
    {
        $module = strtolower($parts[0]);
        $file = APPLICATION_PATH . '/modules/' . $module . '/models/' . $parts[2] .
            '.php';
        if (!is_readable($file))
            throw new Exception('Unable to load class: ' . $class_name . ' in file :' . $file);
        include_once ($file);
        $flag = false;
    }

    //Library
    if ($flag)
    {
        $dir = '';

        for ($i = 0; $i < $count - 1; $i++)
        {
            $dir = $dir . strtolower($parts[$i]) . '/';
        }

        $file = $dir . $parts[$count - 1] . '.php';
        if (!is_readable(realpath(SITE_PATH) . '/library/' . $file))
            throw new Exception('Unable to load class: ' . $class_name);

        include_once ($file);
    }
}

function loadHelper($fileName)
{
    $file = realpath(SITE_PATH) . '/library/helpers/' . $fileName . '.php';
    if (is_readable($file))
        include_once ($file);
}

$bootstrap_path = APPLICATION_PATH.'/configs/Bootstrap.php';
if(is_readable($bootstrap_path))
{
	include_once($bootstrap_path);
	$bootstrap = new Bootstrap();
}